const http = require("http");
const fs = require("fs");
const url = require("url");
const qs = require("querystring");
// 设定路由规则：
    // 数据请求：http://localhost:3000/api
    // 静态资源请求：http://localhost:3000/
http.createServer((req, res)=>{
    if(req.url.includes("/api")){
        dataHandle(req, res);
    }else{
        staticHandle(req, res);
    }

}).listen(3000,()=>{
    console.log("服务器开启成功: http://localhost:3000")
})


function dataHandle(req, res){
    if(req.method === "GET"){
        const obj = url.parse(req.url, true).query;
        fn(req, res, obj);
    }else if(req.method === "POST"){
        let str = "";
        req.on("data",(d)=>{
            str += d;
        })
        req.on("end", ()=>{
            const obj = qs.parse(str);
            fn(req, res, obj);
        })
    }
}

function staticHandle(req, res){
    fs.readFile("./www" + url.parse(req.url).pathname, (err, data)=>{
        if(err){
            res.write("404");
        }else{
            res.write(data);
        }
        res.end();
    })
}

function fn(req, res, data){
    console.log(data);
    res.end();
}


